package com.uduemc.jcms.component;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.uduemc.jcms.config.upload.JcmsUploadConfig;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigAudio;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigAudioSize;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFile;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFileSize;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFlash;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFlashSize;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigImage;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigImageSize;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigVideo;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigVideoSize;
import com.uduemc.jcms.generate.entity.JcmsRepertory;

import cn.hutool.core.io.FileUtil;

@Component
public class RepertoryUtil {

	public static int IMAGE = 1;
	public static int FILE = 2;
	public static int FLASH = 3;
	public static int VIDEO = 4;
	public static int AUDIO = 5;
	public static int OUTSIDELINK = 6;

	@Autowired
	JcmsUploadConfig jcmsUploadConfig;

	/**
	 * 返回访问的路径，Bkd Backend 后台的访问路径
	 * 
	 * @param repertory
	 * @return
	 */
	public String imageSrc(JcmsRepertory repertory) {
		// 需要验证物理文件是否存在，如果不存在则给予一个空图片地址！
		if (repertory.getType().intValue() == IMAGE) {
			return "/jcms-source/" + repertory.getFilepath().replace(File.separator, "/");
		}
		if (repertory.getType().intValue() == FILE) {
			return suffixImage(repertory.getSuffix());
		}
		if (repertory.getType().intValue() == FLASH) {
			return suffixImage(repertory.getSuffix());
		}
		if (repertory.getType().intValue() == VIDEO) {
			return suffixImage(repertory.getSuffix());
		}
		if (repertory.getType().intValue() == AUDIO) {
			return suffixImage(repertory.getSuffix());
		}
		if (repertory.getType().intValue() == OUTSIDELINK) {
			return repertory.getLink();
		}

		return null;
	}

	public String linkUrl(JcmsRepertory repertory) {
		if (repertory.getType().intValue() == IMAGE) {
			return "/jcms-source/" + repertory.getFilepath().replace(File.separator, "/");
		}
		if (repertory.getType().intValue() == FILE && repertory.getSuffix().equals("pdf")) {
			return "/jcms-source/" + repertory.getFilepath().replace(File.separator, "/");
		}
		if (repertory.getType().intValue() == FILE) {
			return "/jcms-source/" + suffixImage(repertory.getSuffix());
		}
		if (repertory.getType().intValue() == VIDEO) {
			return "/jcms-source/" + repertory.getFilepath().replace(File.separator, "/");
		}

		if (repertory.getType().intValue() == AUDIO) {
			return "/jcms-source/" + repertory.getFilepath().replace(File.separator, "/");
		}

		if (repertory.getType().intValue() == OUTSIDELINK) {
			return repertory.getLink();
		}
		return null;
	}

	public String downloadUrl(JcmsRepertory repertory) {
		if (repertory.getType().intValue() == OUTSIDELINK) {
			return repertory.getLink();
		} else {
			return "/jcms-source/repertory/download.html?unidname=" + repertory.getUnidname();
		}
	}

	public String accessUrlByPath(String domain, String path) {
		return accessUrl(domain, path.replace("\\", "/"));
	}

	public String accessUrl(String domain, String uri) {
		return "//" + domain + uri;
	}

	public String suffixImage(String suffix) {
		return "/assets/backend/image/icon_suffix/" + suffix + ".png";
	}

	// ========================================================================================
	/**
	 * 基础上传资源的目录
	 * 
	 * @return
	 */
	public String makeRepertoryPathBasic() {
		return "upload" + File.separator + "repertory" + File.separator;
	}

	/**
	 * 通过时间生成上传的目录
	 * 
	 * @param createAt
	 * @return
	 */
	public String getRepertoryPathByDate(LocalDateTime createAt) {
		String makeRepertoryPathBasic = makeRepertoryPathBasic();
		return makeRepertoryPathBasic + createAt.getYear() + File.separator + createAt.getMonthValue() + File.separator + createAt.getDayOfMonth();
	}

	/**
	 * 通过时间、文件名构建出来上传的相对路径
	 * 
	 * @param createAt
	 * @param originalFilename
	 * @return
	 */
	public String getRepertoryPathByDate(LocalDateTime createAt, String originalFilename) {
		String makeRepertoryPathBasic = makeRepertoryPathBasic();
		return makeRepertoryPathBasic + createAt.getYear() + File.separator + createAt.getMonthValue() + File.separator + createAt.getDayOfMonth()
				+ File.separator + originalFilename;
	}

	/**
	 * 通过文件名构建出当前时间的上传相对路径
	 * 
	 * @param originalFilename
	 * @return
	 */
	public String getRepertoryPathByFilename(String originalFilename) {
		String makeRepertoryPathBasic = makeRepertoryPathBasic();
		LocalDateTime createAt = LocalDateTime.now();
		return makeRepertoryPathBasic + createAt.getYear() + File.separator + createAt.getMonthValue() + File.separator + createAt.getDayOfMonth()
				+ File.separator + originalFilename;
	}

	/**
	 * 完整路径
	 * 
	 * @param createAt
	 * @param originalFilename
	 * @return
	 */
	public String getRepertoryFullPathByDate(LocalDateTime createAt, String originalFilename) {
		String rootpath = jcmsUploadConfig.filepath();
		return rootpath + File.separator + getRepertoryPathByDate(createAt, originalFilename);
	}

	/**
	 * 完整路径
	 * 
	 * @param originalFilename
	 * @return
	 */
	public String getRepertoryFullPathByFilename(String originalFilename) {
		String rootpath = jcmsUploadConfig.filepath();
		return rootpath + File.separator + getRepertoryPathByFilename(originalFilename);
	}

	/**
	 * 完整路径
	 * 
	 * @param path
	 * @return
	 */
	public String getRepertoryFullPathByPath(String path) {
		String rootpath = jcmsUploadConfig.filepath();
		return rootpath + File.separator + path;
	}

	/**
	 * 生成一个真实可用的文件名
	 * 
	 * @param createAt
	 * @param originalFilename
	 * @return
	 */
	synchronized public String makeOriginalFilename(LocalDateTime createAt, String originalFilename) {
		// 通过判断文件是否存在
		String filefullpath = getRepertoryFullPathByDate(createAt, originalFilename);

		File file = new File(filefullpath);
		if (file.isFile()) {
			return makeOriginalFilename(createAt, makeNewOriginalFilename(originalFilename));
		}
		// 创建一个空文件
		FileUtil.touch(filefullpath);
		return originalFilename;
	}

	// 制作新的文件名
	public static String makeNewOriginalFilename(String originalFilename) {
		int lastIndexOf = originalFilename.lastIndexOf(".");
		String start = originalFilename.substring(0, lastIndexOf);
		String end = originalFilename.substring(lastIndexOf);

		if (start.lastIndexOf("(") == -1 || start.lastIndexOf(")") == -1) {
			return start + "(1)" + end;
		} else {
			String numberStart = start.substring(0, start.lastIndexOf("("));
			String numberEnd = start.substring(start.lastIndexOf("("));
			String number = numberEnd.substring(1, numberEnd.lastIndexOf(")"));
			Long num = null;
			try {
				num = Long.valueOf(number);
			} catch (NumberFormatException e) {
			}
			if (num == null) {
				number = "(1)";
				return start + number + end;
			} else {
				number = "(" + (++num) + ")";
				return numberStart + number + end;
			}
		}
	}

	// ========================================================================================
	public boolean allowSuffix(String suffix) {
		List<String> allowSuffix = jcmsUploadConfig.allowSuffix();
		for (String string : allowSuffix) {
			if (suffix.equals(string)) {
				return true;
			}
		}
		return false;
	}

	public String size(MultipartFile file) {
		long size = file.getSize();
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
		JCMSUploadConfigImage image = jcmsUploadConfig.getImage();
		String[] ext = image.getExt();
		if (image.isEnabled() && Arrays.asList(ext).contains(suffix)) {
			JCMSUploadConfigImageSize rulSize = image.getRulSize();
			if (size > rulSize.validSize()) {
				return rulSize.errorMessage();
			}
			return null;
		}

		JCMSUploadConfigFile configFile = jcmsUploadConfig.getFile();
		if (configFile.isEnabled() && Arrays.asList(configFile.getExt()).contains(suffix)) {
			JCMSUploadConfigFileSize rulSize = configFile.getRulSize();
			if (size > rulSize.validSize()) {
				return rulSize.errorMessage();
			}
			return null;
		}

		JCMSUploadConfigFlash flash = jcmsUploadConfig.getFlash();
		if (flash.isEnabled() && Arrays.asList(flash.getExt()).contains(suffix)) {
			JCMSUploadConfigFlashSize rulSize = flash.getRulSize();
			if (size > rulSize.validSize()) {
				return rulSize.errorMessage();
			}
			return null;
		}

		JCMSUploadConfigVideo video = jcmsUploadConfig.getVideo();
		if (video.isEnabled() && Arrays.asList(video.getExt()).contains(suffix)) {
			JCMSUploadConfigVideoSize rulSize = video.getRulSize();
			if (size > rulSize.validSize()) {
				return rulSize.errorMessage();
			}
			return null;
		}

		JCMSUploadConfigAudio audio = jcmsUploadConfig.getAudio();
		if (audio.isEnabled() && Arrays.asList(audio.getExt()).contains(suffix)) {
			JCMSUploadConfigAudioSize rulSize = audio.getRulSize();
			if (size > rulSize.validSize()) {
				return rulSize.errorMessage();
			}
			return null;
		}

		return "未知的上传文件类型！";
	}

	public int type(MultipartFile file) {
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
		JCMSUploadConfigImage image = jcmsUploadConfig.getImage();
		String[] ext = image.getExt();
		if (image.isEnabled() && Arrays.asList(ext).contains(suffix)) {
			return image.getType();
		}

		JCMSUploadConfigFile configFile = jcmsUploadConfig.getFile();
		if (configFile.isEnabled() && Arrays.asList(configFile.getExt()).contains(suffix)) {
			return configFile.getType();
		}

		JCMSUploadConfigFlash flash = jcmsUploadConfig.getFlash();
		if (flash.isEnabled() && Arrays.asList(flash.getExt()).contains(suffix)) {
			return flash.getType();
		}

		JCMSUploadConfigVideo video = jcmsUploadConfig.getVideo();
		if (video.isEnabled() && Arrays.asList(video.getExt()).contains(suffix)) {
			return video.getType();
		}

		JCMSUploadConfigAudio audio = jcmsUploadConfig.getAudio();
		if (audio.isEnabled() && Arrays.asList(audio.getExt()).contains(suffix)) {
			return audio.getType();
		}

		return -1;
	}
}
